/*
 * PsMediaMuxer.cpp
 *
 *  Created on: 2020年4月29日
 *      Author: chuanjiang.zh
 */

#include "PsMediaMuxer.h"
#include "PSMuxer.h"
#include "MediaMuxerPrivate.h"

class PsMediaMuxerPrivate : public MediaMuxerPrivate
{
public:

	av::PSMuxer	m_muxer;

};









PsMediaMuxer::PsMediaMuxer():
	m_pimp(new PsMediaMuxerPrivate())
{
}

PsMediaMuxer::~PsMediaMuxer()
{
	close();

	delete m_pimp;
}

bool PsMediaMuxer::open(const UMediaFormat& fmt)
{
	m_pimp->m_muxer.setCodec(fmt.m_codec, fmt.m_audioCodec);
	m_format = fmt;

	return m_format.isValid();
}

void PsMediaMuxer::close()
{
	m_pimp->m_muxer.clear();
}

bool PsMediaMuxer::isOpen()
{
	return m_format.isValid();
}


bool PsMediaMuxer::getOutFormat(UMediaFormat& fmt)
{
	fmt = m_format;
	return m_format.isValid();
}

bool PsMediaMuxer::input(UMediaPacket& pkt)
{
	if (pkt.size() <= 0)
	{
		return false;
	}

	uint8_t * outData = nullptr;
	int outSize = 0;

	if (pkt.isVideo())
	{
		int64_t pts = pkt.pts() * 90 / 1000;
		m_pimp->m_muxer.writeVideo(pkt.data(), pkt.size(), pkt.isKey(), pts, outData, outSize);
	}
	else if (pkt.isAudio())
	{
		int64_t pts = pkt.pts() * 90 / 1000;
		m_pimp->m_muxer.writeAudio(pkt.data(), pkt.size(), pts, outData, outSize);
	}

	bool got = false;
	if (outData && outSize > 0)
	{
		UMediaPacket packet;
		packet.newPacket(outSize);
		packet.set_type(UMEDIA_TYPE_DATA);
		packet.set_pts(pkt.pts());
		packet.set_dts(pkt.pts());
		packet.set_flags(pkt.flags());
		packet.set_duration(pkt.duration());
		packet.copy(outData, outSize);

		m_pimp->firePacket(packet);
	}

	return got;
}

void PsMediaMuxer::setSink(Sink sink)
{
	m_pimp->setSink(sink);
}


const char* PsMediaMuxer::getName()
{
    return "ps";
}
